package top.yxf.gulimall.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.yxf.common.exception.BizCodeEnum;
import top.yxf.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author yixiangfeng
 * @ClassName GulimallExceptionControllerAdvice
 * @Description 统一处理异常
 * @CreateTime 下午2:18
 **/
@RestControllerAdvice(basePackages = "top.yxf.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验错误[{}],异常类型[{}]", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        if (result.hasErrors()) {
            // 获取校验的错误结果
            result.getFieldErrors().forEach((item) -> {
                String message = item.getDefaultMessage();
                // 获取错误的字段
                String field = item.getField();
                map.put(field, message);

            });
        }
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMessage()).put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R exception(Throwable e) {
        log.error("error is [{}]" , e.getMessage());
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }

}
